package com.one.rope.mvp.web.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.one.rope.mvp.basecore.third.wx.common.WxMiniprogramVO;
import com.one.rope.mvp.basecore.third.wx.common.WxSendMsgRes;
import com.one.rope.mvp.basecore.third.wx.common.WxSendTemplateMsgReq;
import com.one.rope.mvp.basecore.third.wx.common.WxTemplateMsgCotent;
import com.one.rope.mvp.basecore.util.DateUtil;
import com.one.rope.mvp.basecore.util.MyBeanUtils;
import com.one.rope.mvp.basecore.util.StringUtils;
import com.one.rope.mvp.web.business.dao.MemberInfoMapper;
import com.one.rope.mvp.web.business.dao.MemberPushPageMapper;
import com.one.rope.mvp.web.business.entity.MemberInfo;
import com.one.rope.mvp.web.business.entity.MemberPushPage;
import com.one.rope.mvp.web.business.entity.MemberPushTaskLog;
import com.one.rope.mvp.web.business.dao.MemberPushTaskLogMapper;
import com.one.rope.mvp.web.business.service.IMemberPushTaskLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.one.rope.mvp.web.common.dto.admin.push.*;
import com.one.rope.mvp.basecore.bean.AdminBusinessMessage;
import com.one.rope.mvp.basecore.bean.ResponseObject;
import com.one.rope.mvp.web.common.enums.MemberPushStatusEnum;
import com.one.rope.mvp.basecore.exception.BusinessDataException;
import com.one.rope.mvp.web.service.user.WxOfficialService;
import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 推送任务表 服务实现类
 * </p>
 *
 * @author wesley
 * @since 2020-02-20
 */
@Service
public class MemberPushTaskLogServiceImpl extends
    ServiceImpl<MemberPushTaskLogMapper, MemberPushTaskLog> implements IMemberPushTaskLogService {

  @Autowired
  MemberPushTaskLogMapper memberPushTaskLogMapper;

  @Autowired
  MemberPushPageMapper memberPushPageMapper;

  @Autowired
  WxOfficialService wxOfficialService;

  @Autowired
  MemberInfoMapper memberInfoMapper;

  @Override
  public ResponseObject pushTaskList(AdminMemberPushListDTO requestDTO) {
    AdminMemberPushListVO resultVO = new AdminMemberPushListVO();
    Page<AdminMemberPushListItemVO> page = new Page<>(requestDTO.getPageNo(),
        requestDTO.getPageSize());
    List<AdminMemberPushListItemVO> recordList = memberPushTaskLogMapper
        .selectMemberPushTaskListByPage(page, requestDTO);

    resultVO.setResults(recordList);
    resultVO.initPageInfo(page);
    return new ResponseObject(resultVO);
  }

  @Override
  public ResponseObject savePushTask(AdminSaveMemberPushDTO requestDTO) {
    MemberPushTaskLog memberPushTaskLog = new MemberPushTaskLog();
    MyBeanUtils.copyPropertiesIgnoreNull(requestDTO, memberPushTaskLog);
    MemberInfo memberInfo = memberInfoMapper.selectById(requestDTO.getPushTarget());
    memberPushTaskLog.setToOpenId(memberInfo.getWxOfficialOpenId());
    // 新增
    if (null == requestDTO.getId() || requestDTO.getId() == 0) {
      memberPushTaskLog.setId(null);
      this.save(memberPushTaskLog);
    } else {
      // 编辑
      MemberPushTaskLog dbMemberPushTaskLog = this.getById(requestDTO.getId());
      if (dbMemberPushTaskLog.getStatus() == MemberPushStatusEnum.PUSH_SUCCESS.getCode()) {
        throw new BusinessDataException(AdminBusinessMessage.PUSH_LOG_CANNOT_UPDATE);
      }
      this.updateById(memberPushTaskLog);
    }
    return ResponseObject.successObject();
  }

  @Override
  public ResponseObject<AdminMemberPushVO> executePush(Long id) throws Exception{
    AdminMemberPushVO resultVO = new AdminMemberPushVO();
    MemberPushTaskLog dbMemberPushTaskLog = this.getById(id);
    if (dbMemberPushTaskLog.getStatus() == MemberPushStatusEnum.PUSH_SUCCESS.getCode()) {
      throw new BusinessDataException(AdminBusinessMessage.PUSH_LOG_HAVE_EXECUTE);
    }
    if(StringUtils.isNullOrEmpty(dbMemberPushTaskLog.getToOpenId())){
      throw new BusinessDataException(AdminBusinessMessage.PUSH_LOG_OPENID_NOT_NULL);
    }
    MemberPushTaskLog memberPushTaskLog = new MemberPushTaskLog();
    memberPushTaskLog.setId(id);
    // 推送公众号模板消息
    boolean pushStatus = true;
    WxSendTemplateMsgReq msgReq = new WxSendTemplateMsgReq();
    memberPushTaskLog.setPushTime(new Date());
    msgReq.setToUser(dbMemberPushTaskLog.getToOpenId());
    WxMiniprogramVO miniprogramVO = new WxMiniprogramVO();
    miniprogramVO.setPagepath(dbMemberPushTaskLog.getPageUrl());
    msgReq.setMiniprogram(miniprogramVO);
    // 模板消息内容
    WxTemplateMsgCotent msgCotent = new WxTemplateMsgCotent();
    msgCotent.setFirst(dbMemberPushTaskLog.getName());
    msgCotent.setKeyword1("请进入小程序查看详情");
    msgCotent.setKeyword2(DateUtil.dateToString(memberPushTaskLog.getPushTime()));
    msgReq.setMsgCotent(msgCotent);
    WxSendMsgRes msgRes = wxOfficialService.sendTemplateTextMsg(msgReq);
    if(!"0".equals(msgRes.getErrcode())){
      pushStatus = false;
    }
    if (pushStatus) {
      resultVO.setResult(1);
      memberPushTaskLog.setStatus(MemberPushStatusEnum.PUSH_SUCCESS.getCode());
    } else {
      resultVO.setResult(2);
      resultVO.setReason(msgRes.getErrmsg());
      memberPushTaskLog.setStatus(MemberPushStatusEnum.PUSH_FAILURE.getCode());
    }
    // 更新推送状态
    this.updateById(memberPushTaskLog);
    return new ResponseObject(resultVO);
  }

  @Override
  public ResponseObject pushPageList() {
    List<MemberPushPage> pushPageList = memberPushPageMapper.selectList(new QueryWrapper<>());
    List<AdminMemberPushPageVO> resultVO = new ArrayList<>();
    if (pushPageList.size() > 0) {
      pushPageList.stream().forEach(item -> {
        AdminMemberPushPageVO pushPageVO = new AdminMemberPushPageVO();
        MyBeanUtils.copyPropertiesIgnoreNull(item, pushPageVO);
        resultVO.add(pushPageVO);
      });
    }
    return new ResponseObject(resultVO);
  }

  @Override
  public List<MemberPushTaskLog> selectMemberPushList(Long targetId) {
    QueryWrapper<MemberPushTaskLog> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("push_target", targetId);
    queryWrapper.eq("status", MemberPushStatusEnum.PUSH_SUCCESS.getCode());
    queryWrapper.eq("is_delete", 0);
    List<MemberPushTaskLog> pushTaskLogList = memberPushTaskLogMapper.selectList(queryWrapper);
    return pushTaskLogList;
  }
}
